import React, { useEffect, useState } from 'react';
import { Empty, Space, Spin, Tag, message } from 'antd';
import orgCtrl from '@/ts/controller';
import { IApplication, TargetType, IFile } from '@/ts/core';
import RenderCard from './renderCard';
import BannerImg from '../../Common/BannerImg';
import { RightOutlined } from '@ant-design/icons';
import EntityIcon from '@/components/Common/GlobalComps/entityIcon';
import SelectFile from '../../NavigationBar/selectFile';
import { LoadBanner } from '../../Common/bannerDefaultConfig';

const AssetModule: React.FC<{
  onChange: (checkApp: IFile) => void;
  reLoad: boolean;
}> = ({ onChange, reLoad }) => {
  const [loaded, setLoaded] = useState(false);
  const [source, setSource] = useState<IApplication[]>([]);
  const [currentApp, setCurrentApp] = useState<IApplication>();
  const [flag, setFlag] = useState<boolean>(false);
  const [bannerImg, setBannerImg] = useState<any[]>([]);
  const [showSelect, setShowSelect] = useState<boolean>(false);
  const [pages, setPages] = useState<any[]>([]);
  const defaultImgs = LoadBanner('assetModule');
  const getPages = async () => {
    return (await orgCtrl.user.cacheObj.get('portalTemplate')) ?? [];
  };
  const Info = async () => {
    let key = sessionStorage.getItem('homePage') || 2;
    let res: any = await getPages();
    setPages(res);
    let selectXApp: any = res[Number(key) - 2];
    let companyList = [orgCtrl.user, ...orgCtrl.user.companys];
    let checkCompany = companyList.find((item) => {
      if (selectXApp) {
        return item.belongId === selectXApp.belongId;
      } else {
        return undefined;
      }
    });
    if (!checkCompany) {
      setCurrentApp(undefined);
      setSource([]);
      setLoaded(true);
      return;
    }
    const applications: IApplication[] = [];
    for (const target of checkCompany.directory.target.targets) {
      applications.push(...(await target.directory.loadAllApplication()));
    }
    const assetApps = applications.filter(
      (a) => a.directory.target.typeName != TargetType.Storage && !a.metadata.isDeleted,
    );
    if (selectXApp && selectXApp.belongId) {
      const targetApp = assetApps.find(
        (i) => i.id === selectXApp.metadata.id && i.spaceId === selectXApp.belongId,
      );
      setCurrentApp(targetApp);
    } else {
      setCurrentApp(assetApps.length > 0 ? assetApps[0] : undefined);
    }
    setLoaded(true);
  };
  useEffect(() => {
    Info();
    setBannerImg(defaultImgs ?? []);
    // setBannerImg([
    //   {
    //     key: '1',
    //     name: '首页图片',
    //     url: ' /img/home/head.png',
    //   },
    // ]);
  }, []);
  useEffect(() => {
    Info();
    setBannerImg(defaultImgs ?? []);
  }, [reLoad]);
  useEffect(() => {
    if (currentApp) {
      if (currentApp.metadata.banners) {
        setBannerImg([JSON.parse(currentApp.metadata.banners)]);
      } else {
        setBannerImg(defaultImgs ?? []);
        // setBannerImg([
        //   {
        //     key: '1',
        //     name: '首页图片',
        //     url: ' /img/home/head.png',
        //   },
        // ]);
      }
    }
  }, [currentApp]);
  /** 渲染模块 */
  const renderModule = () => {
    if (currentApp) {
      return (
        <React.Fragment>
          {currentApp.sortedChildren.map((item) => (
            <RenderCard key={item.id} app={item} />
          ))}
        </React.Fragment>
      );
    }
    return (
      <div className="cardGroup">
        <div className="cardItem">
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="应用暂无模块" />
        </div>
      </div>
    );
  };

  /** 渲染应用 */
  const renderApp = () => {
    return (
      <React.Fragment>
        <div className="flex">
          {!currentApp && (
            <Space
              style={{
                backgroundColor: '#fff',
                borderRadius: '4px',
                padding: '0 10px',
                // marginRight: '10px',
              }}>
              请选择应用
            </Space>
          )}
          {currentApp && (
            <Space
              style={{
                backgroundColor: '#fff',
                borderRadius: '4px',
                // paddingLeft: '10px',
                // marginLeft: '10px',
                background: '#f7f8fa',
              }}>
              <EntityIcon
                size={30}
                disableInfo
                key={currentApp.id}
                entity={currentApp.metadata}
              />
              <div style={{ color: '#15181D', fontSize: 20 }}>{currentApp.name}</div>
              <div>
                {currentApp.belongTags.map((tag) => (
                  <Tag color="processing" key={tag}>
                    {tag}
                  </Tag>
                ))}
              </div>
            </Space>
          )}
          <div style={{ lineHeight: '39px' }}>
            <span
              style={{
                cursor: 'default',
                color: 'rgba(54, 110, 244, 1)',
                marginRight: 10,
              }}
              onClick={() => setShowSelect(true)}>
              切换
            </span>
            <RightOutlined
              style={{ color: 'rgba(54, 110, 244, 1)' }}
              onClick={() => setShowSelect(true)}
            />
          </div>
        </div>
        <div style={{ width: '100%' }}>
          {currentApp && <BannerImg bannerkey='app' target={currentApp.target.space} bannerImg={bannerImg}></BannerImg>}
        </div>
        {renderModule()}
        {showSelect && (
          <SelectFile
            tagType={'1'}
            onChange={() => {
              setShowSelect(false);
            }}
            onCheck={async (checkApps: any) => {
              if (!checkApps) {
                message.info('请选择');
              }
              let key = sessionStorage.getItem('homePage') ?? 2;
              let res: any = await getPages();
              let item = res[Number(key)-2];
              if (!item) {
                return;
              }
              item.metadata = checkApps?.metadata;
              item.key = 'home_Module' + checkApps.belongId + '_' + checkApps.metadata.id;
              item.id = checkApps.belongId + '_' + checkApps.metadata.id;
              item.name = checkApps.metadata.name;
              item.tags = ['应用模板', checkApps.target.name];
              item.belongId = checkApps.belongId;
              let index = res.findIndex(
                (items: any) => items.metadata.id === item.metadata.id,
              );
              res[index] = item;
              await orgCtrl.user.cacheObj.set('portalTemplate', res);
              setFlag(!flag);
              Info();
              onChange(checkApps);
              setShowSelect(false);
            }}
            pages={pages}></SelectFile>
        )}
      </React.Fragment>
    );
  };
  return (
    <Spin spinning={!loaded} tip={'加载中...'}>
      <div className="workbench-content">{renderApp()}</div>
    </Spin>
  );
};
export default AssetModule;
